package com.atguigu.flink.chapter06;

import com.sun.org.apache.bcel.internal.generic.NEW;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Date;

public class WindowAllDemo {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        env.socketTextStream("hadoop102",8888)
                .flatMap(new FlatMapFunction<String, Tuple2<String,Integer>>() {
                    @Override
                    public void flatMap(String s,
                                        Collector<Tuple2<String, Integer>> out) throws Exception {
                        String[] words = s.split(" ");
                        for (String word : words) {
                            out.collect(Tuple2.of(word,1));
                        }
                    }
                })
                .windowAll(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                //.windowAll(SlidingProcessingTimeWindows.of(Time.seconds(5),Time.seconds(2)))
                .process(new ProcessAllWindowFunction<Tuple2<String, Integer>, String, TimeWindow>() {
                    @Override
                    public void process(Context ctx,
                                        Iterable<Tuple2<String, Integer>> elements,
                                        Collector<String> out) throws Exception {
                        ArrayList<String> list = new ArrayList<>();
                        for (Tuple2<String, Integer> t : elements) {
                            list.add(t.f0 + "_" + t.f1);
                        }
                        String msg = new Date(ctx.window().getStart()) + "," + new Date(ctx.window().getEnd()) + list;
                        out.collect(msg);
                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
